package com.luyuan.crm.formula.service.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;

import com.luyuan.crm.formula.model.Formula;
import com.luyuan.crm.formula.model.Inventory;
import com.luyuan.crm.formula.service.FormulaService;
import com.luyuan.crm.formula.service.InventoryService;
import com.luyuan.crm.product.model.ProductType;
import com.ruijie.foundation.dao.extend.support.HibernateEntityExtendDao;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaQueryTemplate;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;

@SuppressWarnings("unchecked")
public class FormulaServiceImpl extends HibernateEntityExtendDao<Formula> implements FormulaService {

    @Autowired
    private InventoryService inventoryService;

    @Override
    public Page pagedQuery(CriteriaTemplate criteria, int pageNo, int pageSize, List<Order> orders) {
        CriteriaQueryTemplate qt = new CriteriaQueryTemplate(getSessionFactory());
        return qt.pagedQuery(criteria, pageNo, pageSize, orders);
    }

    @Override
    public void deleteByFormulaId(Serializable id) {
        this.remove(id);
    }

    @Override
    public void batchDeleteFormula(Serializable[] ids) {
        this.remove(ids);
    }

    @Override
    public List<Formula> findByProductType(ProductType productType) {
        return find("from Formula where productType = ? and enabled = true", productType);
    }

    @Override
    public void saveFormula(Formula formula) {
        this.save(formula);
        for (Inventory inventory : formula.getInventorys()) {
            this.inventoryService.save(inventory);
            inventory.setFormula(formula);
        }
    }

    @Override
    public void updateFormula(Formula formula) {
        this.update(formula);
        for (Inventory inventory : formula.getInventorys()) {
            this.inventoryService.save(inventory);
            inventory.setFormula(formula);
        }
    }

    @Override
    public void disableByFormulaId(Serializable id) {
        update("update Formula set enabled = false where id = ?", id);
        clear();
    }

    @Override
    public void enableByFormulaId(Serializable id) {
        update("update Formula set enabled = true where id = ?", id);
        clear();
    }
}
